from sqlalchemy.orm import Session
from typing import List, Optional, Dict
from datetime import datetime

from server.db.models.log import Log
from server.schemas.log import LogInDB
from handle.handle_log import log


def create_log(
        db: Session,
        method: str,
        path: str,
        status_code: int,
        user_id: Optional[str] = None,
        params: Optional[str] = None,
        ip_address: Optional[str] = None,
        user_agent: Optional[str] = None,
        response: Optional[str] = None
):
    """创建系统日志记录"""
    try:
        db_log = Log(
            user_id=user_id,
            method=method,
            path=path,
            params=params,
            ip_address=ip_address,
            user_agent=user_agent,
            status_code=status_code,
            response=response
        )
        db.add(db_log)
        db.commit()
        db.refresh(db_log)
    except Exception as e:
        db.rollback()
        log.error(f"创建日志失败: {str(e)}")


def get_log(db: Session, log_id: str) -> Optional[LogInDB]:
    """获取单个日志记录"""
    try:
        db_log = db.query(Log).filter(Log.id == log_id).first()
        return LogInDB.from_orm(db_log) if db_log else None
    except Exception as e:
        log.error(f"获取日志失败: {str(e)}")





